package com.onlyxiahui.framework.net.session.server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.onlyxiahui.framework.net.session.SessionBox;
import com.onlyxiahui.framework.net.session.SocketSession;
import com.onlyxiahui.framework.net.session.server.DataItem.Type;

/**
 * Date 2018-12-30 13:06:14<br>
 * Description
 *
 * @author XiaHui<br>
 * @since 1.0.0
 */
public class DataSendHandler {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final SessionBox sessionBox;

    public DataSendHandler(SessionBox sessionBox) {
        this.sessionBox = sessionBox;
    }

    public void send(DataItem dataQueue) {
        try {
            sendMessage(dataQueue);
        } catch (Exception e) {
            logger.error("消息发送异常！", e);
        }
    }

    private void sendMessage(DataItem dataQueue) {
        if (null != dataQueue) {
            List<String> keyList = dataQueue.getKeyList();

            if (dataQueue.getType() == Type.one || dataQueue.getType() == Type.list) {
                if (null != keyList) {
                    for (String key : keyList) {
                        Set<SocketSession> set = sessionBox.getSet(key);
                        sendMessage(set, dataQueue);
                    }
                }
            } else if (dataQueue.getType() == Type.all) {
                sendMessage(sessionBox.getAllSet(), dataQueue);
            } else if (dataQueue.getType() == Type.without) {
                int size = (null == keyList) ? 0 : keyList.size();
                Map<String, String> map = new HashMap<>(size);
                if (null != keyList) {
                    for (String key : keyList) {
                        map.put(key, key);
                    }
                }
                for (SocketSession sd : sessionBox.getAllSet()) {
                    if (!map.containsKey(sd.getKey())) {
                        sendMessage(sd, dataQueue);
                    }
                }
            }
        }
    }

    private void sendMessage(Set<SocketSession> set, DataItem dataQueue) {
        if (null != set) {
            for (SocketSession sd : set) {
                sendMessage(sd, dataQueue);
            }
        }
    }

    private void sendMessage(SocketSession socketSession, DataItem dataQueue) {
        if (null != socketSession) {
            write(socketSession, dataQueue.getData());
        }
    }

    private void write(SocketSession socketSession, Object data) {
        if (null != socketSession && null != data) {
            try {
                socketSession.write(data);
            } catch (Exception e) {
                logger.error("", e);
            }
        }
    }
}
